package com.fyx.timedTask;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fyx.config.*;
import com.fyx.entity.*;
import com.fyx.mapper.*;
import com.fyx.modules.system.domain.User;
import com.fyx.modules.system.repository.UserRepository;
import com.fyx.until.DateUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 运营数据
 */
@Slf4j
@Component(value="RunDataTask")
public class RunDataTask {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = SecondaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate secondaryMongoTemplate;

    @Resource(name = SixthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate sixthMongoTemplate;

    @Resource(name = TenthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate tenthMongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;

    @Autowired
    private LostGoldMapper lostGoldMapper;

    @Autowired
    private DiamondCountMapper diamondCountMapper;

    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    @Autowired
    private GoldRecCountMapper goldRecCountMapper;

    @Autowired
    private AnchorInfoMapper anchorInfoMapper;

    @Autowired
    private UserRepository userRepository;


    public void run(){
        long beginTime=DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        if((beginTime+3600)>nowTime){
            beginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        }
        String tableName=DateUtil.timeStamp2Date(beginTime+"","yyyyMM");;
        if(beginTime==nowTime){
            if(!DateUtil.timeStamp2Date(beginTime+"","yyyyMM").equals(DateUtil.timeStamp2Date(nowTime+"","yyyyMM"))){
                tableName =DateUtil.timeStamp2Date(beginTime+"","yyyyMM");
            }
        }
    //    beginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        long endTime=beginTime+86400;
        recordAnchor(beginTime,endTime,tableName);
        recordLostGold(beginTime,endTime,nowTime);
        bankruptcy(beginTime,tableName,nowTime);
        log.info("运营数据任务：执行完毕=======================");
    }
    public void recordAnchor( long beginTime,long endTime,String tab){
        List<User> list=userRepository.findByBindGameId();
        if(list.size()>0){
            for(User user:list){
                AnchorInfo anchorInfo=new AnchorInfo();
               anchorInfo.setAnchorId(user.getBindGameId());
               anchorInfo.setTime(beginTime);
               anchorInfo.setCreateTime(user.getCreateTime().getTime()/1000);
               Criteria criteria=new Criteria();
                criteria.and("anchor_id").is(user.getBindGameId());
                criteria.and("reg_time").gte(beginTime-86400).lt(endTime);
                criteria.and("set_anchor_time").gte(beginTime).lt(endTime);
                List<UserEntity> mgUserList= mongoTemplate.find(new Query().addCriteria(criteria),UserEntity.class);
                String[] userArray=new String[mgUserList.size()];
                if(mgUserList.size()>0) {
                    for (int i=0;i<userArray.length;i++) {
                        userArray[i]=mgUserList.get(i).getUserid();
                    }
                }
                anchorInfo.setPerson(mgUserList.size());
                criteria=new Criteria();
                Aggregation aggregation;
                AggregationResults<StaticeEntity> ar;
                List<StaticeEntity> userList;
                if(userArray.length==0){
                    anchorInfo.setNewUserCount(0);
                    anchorInfo.setNewUserPay(0);

                }else {
                    criteria.and("pid").in(userArray);
                    criteria.and("time_end").gte(beginTime).lt(endTime);
                    aggregation = Aggregation.newAggregation(
                            Aggregation.match(criteria),
                            Aggregation.group().count().as("v1").sum("total_fee").as("v2")
                    );
                    ar = mongoTemplate.aggregate(aggregation, "order", StaticeEntity.class);
                    userList = ar.getMappedResults();
                    if (userList.size() > 0) {
                        anchorInfo.setNewUserCount(userList.get(0).getV1());
                        anchorInfo.setNewUserPay(userList.get(0).getV2());
                    }
                }
                criteria=new Criteria();
                criteria.and("anchor_id").is(user.getBindGameId());
                criteria.and("last_time").gte(beginTime).lt(endTime);
                 aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                         Aggregation.group().count().as("v1")
                );
                ar = mongoTemplate.aggregate(aggregation, "user", StaticeEntity.class);
                userList=ar.getMappedResults();
                if(userList.size()>0){
                    anchorInfo.setActNum(userList.get(0).getV1());
                }
                UserEntity userEntity=mongoTemplate.findOne(new Query(Criteria.where("userid").is(user.getBindGameId())),UserEntity.class);
                if(userEntity!=null&&userEntity.getLiving()!=null) {
                    anchorInfo.setAnchorPlay(Integer.parseInt(userEntity.getLiving().get("round").toString()));
                    anchorInfo.setAnchorTime(Integer.parseInt(userEntity.getLiving().get("time").toString()));
                    anchorInfo.setAnchorName(userEntity.getNickname());
                    anchorInfo.setAnchorUser(userEntity.getMarkNum());
                }
                criteria=new Criteria();
                criteria.and("pid").is(user.getBindGameId());
                criteria.and("time_end").gte(beginTime).lt(endTime);
                aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().sum("total_fee").as("v1")
                );
                ar = mongoTemplate.aggregate(aggregation, "order", StaticeEntity.class);
                userList=ar.getMappedResults();
                if(userList.size()>0){
                    anchorInfo.setPaySelf(userList.get(0).getV1()/100);
                }else {
                    anchorInfo.setPaySelf(0);
                }
                QueryWrapper<AnchorInfo>  wrapper=new QueryWrapper();
                wrapper.eq("anchor_id",anchorInfo.getAnchorId());
                wrapper.eq("time",beginTime);
                AnchorInfo anchorInfo1=anchorInfoMapper.selectOne(wrapper);

                if(anchorInfo1==null){
                  anchorInfoMapper.insert(anchorInfo);
                }else {
                    anchorInfoMapper.update(anchorInfo,wrapper);
                }
                anchorInfo=new AnchorInfo();
                criteria=new Criteria();
                criteria.and("anchor_id ").is(user.getBindGameId());
                criteria.and("last_time").gte(beginTime).lt(endTime);
                criteria.and("reg_time").gte(beginTime-86400).lt(beginTime);
                aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().count().as("v1")
                );
                ar = mongoTemplate.aggregate(aggregation, "user", StaticeEntity.class);
                userList=ar.getMappedResults();
                if(userList.size()>0){
                    anchorInfo.setNewUser(userList.get(0).getV1());
                }
                wrapper=new QueryWrapper();
                wrapper.eq("anchor_id",user.getBindGameId());
                wrapper.eq("time",beginTime-86400);
                if(anchorInfo.getNewUser()!=null) {
                    anchorInfoMapper.update(anchorInfo, wrapper);
                }
                criteria=new Criteria();
                anchorInfo=new AnchorInfo();
                criteria.and("anchor_id ").is(user.getBindGameId());
                criteria.and("last_time").gte(beginTime).lt(endTime);
                criteria.and("reg_time").gte(beginTime-86400*3).lt(beginTime-86400*2);
                aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().count().as("v1")
                );
                ar = mongoTemplate.aggregate(aggregation, "user", StaticeEntity.class);
                userList=ar.getMappedResults();
                if(userList.size()>0){
                    anchorInfo.setNewUsers(userList.get(0).getV1());
                }
                wrapper=new QueryWrapper();
                wrapper.eq("anchor_id",user.getBindGameId());
                wrapper.eq("time",beginTime-86400*3);
                if(anchorInfo.getNewUsers()!=null) {
                    anchorInfoMapper.update(anchorInfo, wrapper);
                }
            }
        }

    }

    public void recordLostGold(long beginTime,long endTime,long nowTime){
        String[] str=new String[40];
        String strLost="";
        str[0]="1@100000";str[1]="100001@500000";str[2]="500001@1000000";
        str[3]="1000001@2000000";str[4]="2000001@5000000";str[5]="5000001@10000000";
        str[6]="10000001@50000000";str[7]="50000001@100000000";str[8]="100000001@500000000";
        str[9]="500000001@5000000000";str[10]="5000000001@10000000000";str[11]="10000000001@50000000000";
        str[12]="50000000001@100000000000";str[13]="100000000001@500000000000";str[14]="500000000001@1000000000000";
        str[15]="1000000000001@5000000000000";str[16]="5000000000001@50000000000000";str[17]="50000000000001@500000000000000";
        str[18]="500000000000001@5000000000000000";str[19]="5000000000000001@";
        str[20]="0@-100000";str[21]="-100001@-500000";str[22]="-500001@-1000000";
        str[23]="-1000001@-2000000";str[24]="-2000001@-5000000";str[25]="-5000001@-10000000";
        str[26]="-10000001@-50000000";str[27]="-50000001@-100000000";str[28]="-100000001@-500000000";
        str[29]="-500000001@-5000000000";str[30]="-5000000001@-10000000000";str[31]="-10000000001@-50000000000";
        str[32]="-50000000001@-100000000000";str[33]="-100000000001@-500000000000";str[34]="-500000000001@-1000000000000";
        str[35]="-1000000000001@-5000000000000";str[36]="-5000000000001@-50000000000000";str[37]="-50000000000001@-500000000000000";
        str[38]="-500000000000001@-5000000000000000";str[39]="-5000000000000001@";
        QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", 16);
        wrapper.eq("dict_sort", 900).or().eq("dict_sort",910).or().eq("dict_sort",920).or().eq("dict_sort",999);
        List<SysDictDetail> list5 = sysDictDetailMapper.selectList(wrapper);
        for (SysDictDetail sysDictDetail:list5) {
            for (int i = 0; i < str.length; i++) {
                Criteria criteria = new Criteria();
                if(sysDictDetail.getDictSort()==900||sysDictDetail.getDictSort()==910||sysDictDetail.getDictSort()==920){
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                }
                criteria.and("unix_time").gte(nowTime - 3600).lte(nowTime);
//                criteria.and("unix_time").gte(beginTime).lte(endTime);
                if (str[i].split("@").length < 2) {
                    if (str[i].split("@")[0].indexOf("-") > -1) {
                        criteria.and("change_num").lte(Long.valueOf(str[i].split("@")[0]));
                    } else {
                        criteria.and("change_num").gte(Long.valueOf(str[i].split("@")[0]));
                    }
                } else {
                    if (str[i].split("@")[1].indexOf("-") > -1) {
                        criteria.and("change_num").lte(Long.valueOf(str[i].split("@")[0])).gte(Long.valueOf(str[i].split("@")[1]));
                    } else {
                        criteria.and("change_num").gte(Long.valueOf(str[i].split("@")[0])).lte(Long.valueOf(str[i].split("@")[1]));
                    }
                }
                criteria.and("types").ne(5);
                Aggregation aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().count().as("change_num"),
                        Aggregation.group().sum("change_num").as("v1")
                );
                AggregationResults<StaticeEntity> ar;
                if(sysDictDetail.getDictSort()==910||sysDictDetail.getValue().equals("totalcl")){
                    ar = sixthMongoTemplate.aggregate(aggregation, "dw_ppl_game_detail_di", StaticeEntity.class);
                }else if(sysDictDetail.getDictSort()==920||sysDictDetail.getValue().equals("totalapp")){
                    ar = tenthMongoTemplate.aggregate(aggregation, "dw_ppl_game_detail_di", StaticeEntity.class);
                }
                else {
                    ar = secondaryMongoTemplate.aggregate(aggregation, "dw_ppl_game_detail_di", StaticeEntity.class);
                }
                List<StaticeEntity> list1 = ar.getMappedResults();
                if (list1.size() > 0) {
                    strLost += list1.get(0).getV1() + "@";
                } else {
                    strLost += "0@";
                }
            }
            LostGold lostGold = new LostGold();
            lostGold.setTime(Long.valueOf(beginTime).intValue());
            lostGold.setChannel(sysDictDetail.getValue());
            lostGold.setLostGold(strLost);
            lostGold.setFlag("lostGold");
            strLost="";
            QueryWrapper<LostGold> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("time", beginTime);
            wrapper1.eq("channel", sysDictDetail.getValue());
            wrapper1.eq("flag","lostGold");
            LostGold lostGold1 = lostGoldMapper.selectOne(wrapper1);
            if (lostGold1 == null) {
                lostGoldMapper.insert(lostGold);
            } else {
                String[] str1 = lostGold1.getLostGold().split("@");
                String st = "";
                String[] str2= lostGold.getLostGold().split("@");
                for (int i = 0; i < str1.length; i++) {
                    st += (Integer.parseInt(str1[i]) + Integer.parseInt(str2[i])) + "@";
                }
                lostGold.setLostGold(st);
                lostGoldMapper.update(lostGold, wrapper1);
            }
        }
    }

    public void bankruptcy(long beginTime,String tableName,long nowTime){
        String[] str=new String[20];
        tableName="dw_ppl_game_detail_di";
        String strLost="";
        str[0]="0@-100000";str[1]="-100001@-500000";str[2]="-500001@-1000000";
        str[3]="-1000001@-2000000";str[4]="-2000001@-5000000";str[5]="-5000001@-10000000";
        str[6]="-10000001@-50000000";str[7]="-50000001@-100000000";str[8]="-100000001@-500000000";
        str[9]="-500000001@-5000000000";str[10]="-5000000001@-10000000000";str[11]="-10000000001@-50000000000";
        str[12]="-50000000001@-100000000000";str[13]="-100000000001@-500000000000";str[14]="-500000000001@-1000000000000";
        str[15]="-1000000000001@-5000000000000";str[16]="-5000000000001@-50000000000000";str[17]="-50000000000001@-500000000000000";
        str[18]="-500000000000001@-5000000000000000";str[19]="-5000000000000001@";
        QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", 16);
        wrapper.eq("dict_sort", 900).or().eq("dict_sort",910).or().eq("dict_sort",920).or().eq("dict_sort",999);
        List<SysDictDetail> list5 = sysDictDetailMapper.selectList(wrapper);
        for (SysDictDetail sysDictDetail:list5) {
            for (int i = 0; i < str.length; i++) {
                Criteria criteria = new Criteria();
                if(sysDictDetail.getDictSort()!=999) {
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                }
                criteria.and("unix_time").gte(nowTime - 3600).lte(nowTime);
                criteria.and("fin_num").is(0);
//                criteria.and("unix_time").gte(beginTime).lte(beginTime+86399);
                if (str[i].split("@").length < 2) {
                    if (str[i].split("@")[0].indexOf("-") > -1) {
                        criteria.and("change_num").lte(Long.valueOf(str[i].split("@")[0]));
                    } else {
                        criteria.and("change_num").gte(Long.valueOf(str[i].split("@")[0]));
                    }
                } else {
                    if (str[i].split("@")[1].indexOf("-") > -1) {
                        criteria.and("change_num").lte(Long.valueOf(str[i].split("@")[0])).gte(Long.valueOf(str[i].split("@")[1]));
                    } else {
                        criteria.and("change_num").gte(Long.valueOf(str[i].split("@")[0])).lte(Long.valueOf(str[i].split("@")[1]));
                    }
                }
                Aggregation aggregation = Aggregation.newAggregation(
                       Aggregation.match(criteria),
                        Aggregation.group().count().as("v1")
                );
                AggregationResults<StaticeEntity> ar ;
                if(sysDictDetail.getValue().equals("totalcl")||sysDictDetail.getDictSort()==910) {
                    ar = sixthMongoTemplate.aggregate(aggregation, tableName, StaticeEntity.class);
                }else if(sysDictDetail.getValue().equals("totalapp")||sysDictDetail.getDictSort()==920) {
                    ar = tenthMongoTemplate.aggregate(aggregation, tableName, StaticeEntity.class);
                }else {
                    ar = secondaryMongoTemplate.aggregate(aggregation, tableName, StaticeEntity.class);
                }
                List<StaticeEntity> list1 = ar.getMappedResults();
                if (list1.size() > 0) {
                    strLost += list1.get(0).getV1() + "@";
                } else {
                    strLost += "0@";
                }
            }
            LostGold lostGold = new LostGold();
            lostGold.setTime(Long.valueOf(beginTime).intValue());
            lostGold.setChannel(sysDictDetail.getValue());
            lostGold.setLostGold(strLost);
            lostGold.setFlag("bankruptcy");
            strLost="";
            QueryWrapper<LostGold> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("time", beginTime);
            wrapper1.eq("channel", sysDictDetail.getValue());
            wrapper1.eq("flag","bankruptcy");
            LostGold lostGold1 = lostGoldMapper.selectOne(wrapper1);
            if (lostGold1 == null) {
                lostGoldMapper.insert(lostGold);
            } else {
                String[] str1 = lostGold1.getLostGold().split("@");
                String st = "";
                String[] str2= lostGold.getLostGold().split("@");
                for (int i = 0; i < str1.length; i++) {
                    st += (Integer.parseInt(str1[i]) + Integer.parseInt(str2[i])) + "@";
                }
                lostGold.setLostGold(st);
                lostGoldMapper.update(lostGold, wrapper1);
            }
        }
    }
    public void record(){
        //游戏对局输分
        List<LostGold> list = new ArrayList<>();
        long time = DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        if(time==nowTime){

            time=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        }


        //钻石统计
        QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", 16);
        wrapper.le("dict_sort", 100).or().eq("dict_sort", 900);
        wrapper.orderByDesc("dict_sort");
        List<SysDictDetail> sysDictDetailList = sysDictDetailMapper.selectList(wrapper);
        SysDictDetail sysDictDetail1 = new SysDictDetail();
        sysDictDetail1.setValue("total");
        sysDictDetail1.setDictSort(99);
        sysDictDetailList.add(sysDictDetail1);
        for(SysDictDetail sysDictDetail:sysDictDetailList) {
            DiamondCount diamondCount = new DiamondCount();
            diamondCount.setTime(time);
            //总钻石量
            Criteria  criteria = new Criteria();
            if (!sysDictDetail.getValue().equals("total")) {
                if (sysDictDetail.getDictSort() == 900) {
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                } else {
                    criteria.and("channel").is(sysDictDetail.getValue());
                }
            }
            Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.group().sum("diamond").as("diamond"),
                    Aggregation.project("diamond")
            );
            AggregationResults<UserEntity> ar = mongoTemplate.aggregate(aggregation, "user", UserEntity.class);
            List<UserEntity> list1 = ar.getMappedResults();
            if (list1.size() > 0) {
                diamondCount.setAllDiamond(list1.get(0).getDiamond());
            }

            String collectionName = "diamond_rec_";
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM");
            String dateStr = ft.format(DateUtil.getDayBegin());
            dateStr = dateStr.replace("-", "").trim();
            collectionName = collectionName + dateStr;

            //钻石总购买
            criteria = new Criteria();
            if (!sysDictDetail.getValue().equals("total")) {
                if (sysDictDetail.getDictSort() == 900) {
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                } else {
                    criteria.and("channel").is(sysDictDetail.getValue());
                }
            }
            criteria.and("way").is(1);
            criteria.and("time").gte(time);
            Aggregation aggregation1 = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.group().sum("num").as("num"),
                    Aggregation.project("num")
            );
            AggregationResults<DiamondRecEntity> ar1 = secondaryMongoTemplate.aggregate(aggregation1, collectionName, DiamondRecEntity.class);
            List<DiamondRecEntity> list2 = ar1.getMappedResults();
            if (list2.size() > 0) {
                diamondCount.setBuyDiamond(list2.get(0).getNum());
            }

            //钻石总赠送暂时先放着

            //钻石总回收
            criteria = new Criteria();
            if (!sysDictDetail.getValue().equals("total")) {
                if (sysDictDetail.getDictSort() == 900) {
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                } else {
                    criteria.and("channel").is(sysDictDetail.getValue());
                }
            }
            criteria.and("way").is(21);
            criteria.and("time").gte(time);
            aggregation1 = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.group().sum("num").as("num"),
                    Aggregation.project("num")
            );
            ar1 = secondaryMongoTemplate.aggregate(aggregation1, collectionName, DiamondRecEntity.class);
            list2 = ar1.getMappedResults();
            if (list2.size() > 0) {
                diamondCount.setRecycleDiamond(list2.get(0).getNum());
            }

            //活跃人数总钻石
            criteria = new Criteria();
            if (!sysDictDetail.getValue().equals("total")) {
                if (sysDictDetail.getDictSort() == 900) {
                    criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
                } else {
                    criteria.and("channel").is(sysDictDetail.getValue());
                }
            }
            criteria.and("last_time").gte(time).lte(time+86400);
            aggregation = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.group().sum("diamond").as("diamond"),
                    Aggregation.project("diamond")
            );
            ar = mongoTemplate.aggregate(aggregation, "user", UserEntity.class);
            list1 = ar.getMappedResults();
            if (list1.size() > 0) {
                diamondCount.setActiveDiamond(list1.get(0).getDiamond());
            }
            diamondCount.setChannel(sysDictDetail.getValue());
            diamondCount.setTime(time);
            if (!sysDictDetail.getValue().equals("total") && sysDictDetail.getDictSort() != 900) {
                diamondCount.setTheFather(sysDictDetail.getValue().split("_")[0].replace("h5", "") + "_total");
            } else if (sysDictDetail.getDictSort() == 900) {
                diamondCount.setTheFather("total");
            }
            QueryWrapper<DiamondCount> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("channel", diamondCount.getChannel());
            wrapper2.eq("time", time);
            if(diamondCount.getTheFather()!=null) {
                wrapper2.eq("the_father", diamondCount.getTheFather());
            }
            DiamondCount diamondCount1 = diamondCountMapper.selectOne(wrapper2);
            if (diamondCount1 == null) {
                diamondCountMapper.insert(diamondCount);
            } else {
                diamondCountMapper.update(diamondCount, wrapper2);
            }

        }

    }
}
